package com.zhouyu.nettysvr.config;

import com.zhouyu.nettysvr.handler.ProtobufServerHandler;
import com.zhouyu.nettysvr.proto.PeopleProto;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

/**
 * @Description:服务端配置
 */
@Component
@Data
@Log4j2
public class ProtoServerConfig implements ApplicationRunner, ApplicationListener<ContextClosedEvent> {

    private int port = 8088;
    private Channel channel;
    private EventLoopGroup boss = new NioEventLoopGroup(1);
    private EventLoopGroup work = new NioEventLoopGroup(4);

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //启动netty服务端
        start();
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
        if(channel!=null){
            log.info("netty服务端关闭!");
            channel.close();
        }
    }

    public void start() throws InterruptedException {
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss, work);

            serverBootstrap.channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) {
                    //推荐的做法：OutboundHandler使用addFirst;InboundHandler使用addLast;那么以下的运行顺序就会按照编译顺序执行。
                    socketChannel.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                    socketChannel.pipeline().addLast(new ProtobufDecoder(PeopleProto.People.getDefaultInstance()));
                    socketChannel.pipeline().addLast(new ProtobufServerHandler());

                    socketChannel.pipeline().addFirst(new ProtobufEncoder());
                    socketChannel.pipeline().addFirst(new ProtobufVarint32LengthFieldPrepender());
                }
            });
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            if (channelFuture.isSuccess()) {
                log.info("netty服务端启动成功");
            }
            channel = channelFuture.channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("netty服务端建立异常",e);
        }finally {
            //优雅的退出，释放资源
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }
    }
}
